﻿using Autofac.Configuration;
using Autofac.Extras.DynamicProxy;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Test1.Core.Interface;
using Test1.Core.Service;

namespace Autofac.Web.Utility
{
    public class CustomAutofacModule: Autofac.Module
    {
        protected override void Load(ContainerBuilder containerBuilder)
        {
            #region 指定控制器也由autofac来进行实例获取

            var assembly = this.GetType().GetTypeInfo().Assembly;
            //var builder = new ContainerBuilder();

            //var manager = new ApplicationPartManager();
            //manager.ApplicationParts.Add(new AssemblyPart(assembly));
            //manager.FeatureProviders.Add(new ControllerFeatureProvider());

            //var feature = new ControllerFeature();
            //manager.PopulateFeature(feature);
            //builder.RegisterType<ApplicationPartManager>().AsSelf().SingleInstance();
            //builder.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired();

            #endregion
            //指定服务的注册
            //containerBuilder.RegisterType<TestServiceA>().As<ITestServiceA>();
            //containerBuilder.RegisterType<TestServiceB>().As<ITestServiceB>();
            //containerBuilder.RegisterType<TestServiceC>().As<ITestServiceC>();

            #region Autofac基于配置文件的服务注册
            //Json格式配置文件
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.AddJsonFile("Config/autofac.json");
            IConfigurationRoot root= configurationBuilder.Build();

            //开始读取配置文件里的内容信息
            ConfigurationModule module = new ConfigurationModule(root);
            //根据配置文件的内容注册服务
            containerBuilder.RegisterModule(module);
            //IContainer container = containerBuilder.Build();
            //ITestServiceA testServiceA = container.Resolve<ITestServiceA>();

            #endregion

            #region autofac 支持Aop

            
            containerBuilder.Register(a => new CustomAutofacAop());//标识允许Autofac使用Aop
            containerBuilder.RegisterType<TestAutofac>().As<ITestAutofac>().EnableInterfaceInterceptors();


            #endregion

        }


    }
}
